const Controller = require('egg').Controller;


class access extends Controller {

    async index(){
        const {app,ctx,service} = this;
        // console.info(ctx.state);
        await ctx.render('/admin/dashboard.ejs',{});
    }

    async tologin(){
        const {app,ctx,service} = this;

        await ctx.render('/admin/login.ejs');
    }

    async login(){
        const {app,ctx,service} = this;
        let user = ctx.request.body.data;
        let res = await service.userService.login(user);

        ctx.body = {
            code : 200,
            data : {},
            msg : ''
        }
    }

    async logout(){
        const {app,ctx,service} = this;
        ctx.session.user_info = null;
        ctx.session.token = null;
        ctx.body = {
            code : 200,
            data : {},
            msg : ''
        }
    }

    async topassword(){
        const {app,ctx,service} = this;
        await ctx.render('/admin/safety_edit.ejs');
    }

    async change(){
        const {app,ctx,service} = this;
        let id = ctx.session.user_info.id;
        let param = ctx.request.body.data;
        param.id = id;

        const rule = {
            oldpassword:'required',
            password:'required',
            repassword:{confirmed:'password'}
        };
        const err = await app.validator.validate(param,rule);

        //判断验证结果
        if(!app.lodash.isEmpty(err)){
            //抛出验证错误信息
            ctx.throw(401,err[0].field+' -- '+err[0].message);
        }

        //调用service获取结果
        let rs = await service.userService.update(param);

        //判断处理结果
        if(!rs){
            //抛出处理失败错误信息
            ctx.throw(501,'原密码不正确');
        }

        ctx.body = {
            code : 200,
            data : {},
            msg : ''
        }
    }

    async query(){
        const {app,ctx,service} = this;
        let id = ctx.request.query.id;
        console.info(ctx.request.query)
        console.info(ctx.query)
        console.info(ctx.params)
        const rule = {
            username:'required|alpha:2',//仅支持字母，长度2
            // sex:["man","women"],//必选字段，且值只能为数组中的某一个
            // phone:'phone', // 非必选字段，
            // captcha:'captcha:4' //非必选
            // password:'password' // 非必选
        };
        const err = await app.validator.validate(ctx.query,rule);
        console.info(err)
        ctx.body = {
            code : 200,
            data : {id:id},
            msg : ''
        }
    }
}

module.exports = access;
